package com.wanxin.car.util.helper.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * ͨ��������Ӳ����������
 * @author lqk
 *
 */
public class CodeHelperImpl extends CodeHelperBase{


	/**
	 * �ڿ���̨���ʵ����
	 * 
	 * @param springAppCtxName
	 *            ���spring context�� new
	 *            ClassPathXmlApplicationContext(springAppCtxName)
	 * @param dataSourceId
	 *            spring��Ҫʹ�õ����Դid
	 * @param table
	 *            ����
	 */
	public void printEntity(String springAppCtxName, String dataSourceId, String table) {

		springAppCtxName = springAppCtxName == null ? "applicationContext.xml" : springAppCtxName;
		dataSourceId = dataSourceId == null ? "dataSource" : dataSourceId;
		/*
		 * @Id @GeneratedValue(generator="my") @GenericGenerator(name="my",
		 * strategy="uuid")
		 */

		ApplicationContext ctx = new ClassPathXmlApplicationContext(springAppCtxName);
		DataSource ds = (DataSource) ctx.getBean(dataSourceId);
		Connection conn = null;
		Statement stm = null;
		ResultSet rs = null;
		try {
			conn = ds.getConnection();
			stm = conn.createStatement();
			rs = stm.executeQuery("select * from " + table);
			ResultSetMetaData meta = rs.getMetaData();
			int count = meta.getColumnCount();

			// ���id������Ϣ
			System.out.println("/*");
			System.out.println("@Id");
			System.out.println("@GeneratedValue(generator=\"my\")");
			System.out.println("@GenericGenerator(name=\"my\", strategy=\"uuid\")");
			System.out.println("*/");

			for (int i = 1; i <= count; i++) {

				String columnName = meta.getColumnName(i);
				int columnType = meta.getColumnType(i);

				String field = "private " + getJavatype(columnType) + " " + getJavaname(columnName) + ";";
				String annotation = "@Column(name=\"" + columnName + "\")";

				System.out.println(annotation);
				System.out.println(field);
				System.out.println();
			}

		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			if (rs != null)
				try {
					rs.close();
				} catch (SQLException e1) {
					e1.printStackTrace();
				}

			if (stm != null)
				try {
					stm.close();
				} catch (SQLException e1) {
					e1.printStackTrace();
				}

			if (conn != null)
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
		}
	}
	
	/**
	 * ���ʵ����dao
	 * 
	 * @param entity
	 */
	public void printEntityDao(Class entity) {

		String tab = TAB;// �����

		// hibernateTemplate
		System.out.println("@Resource(name=\"hibernateTemplate\")");
		System.out.println("protected HibernateTemplate ht;");
		System.out.println();

		// ��ɾ�Ĳ鷽��
		String entityClassName = entity.getSimpleName();
		System.out.println("@Transactional");
		System.out.println("public void save(" + entityClassName + " entity){");
		System.out.println(tab + "ht.saveOrUpdate(entity);");
		System.out.println("}");
		System.out.println();

		System.out.println("@Transactional");
		System.out.println("public void delete(" + entityClassName + " entity){");
		System.out.println(tab + "ht.delete(entity);");
		System.out.println("}");
		System.out.println();

		System.out.println("public List<" + entityClassName + "> gets(){");
		System.out.println(tab + "return ht.find(\"from " + entityClassName + "\");");
		System.out.println("}");
		System.out.println();
		
		System.out.println("public " + entityClassName + " get(String id){");
		System.out.println(tab + "return (" + entityClassName + ") ht.get(" + entityClassName + ".class,id);");
		System.out.println("}");
		System.out.println();

		// hibernateTemplate set get
		System.out.println("//---------------------------- set get");
		System.out.println("public HibernateTemplate getHt() {");
		System.out.println(tab + "return ht;");
		System.out.println("}");
		System.out.println("public void setHt(HibernateTemplate ht) {");
		System.out.println(tab + "this.ht = ht;");
		System.out.println("}");

	}
	
	/**
	 * ���action��
	 * 
	 * @param action
	 *            strutr2�Զ�ӳ���action��·��
	 * @param entity
	 * @param dao
	 */
	public void printEntityAction(String action, Class entity, Class dao) {

		String entityClassName = entity.getSimpleName();
		String daoClassName = dao.getSimpleName();

		// ��עaction���
		String tab = TAB;
		System.out.println("@Results(value={");
		System.out.println(tab + "@Result(name=\"listAction\",type=\"redirect\",location=\"/" + action + "/action/"
				+ action + "!list.action\")");
		System.out.println("})");
		System.out.println();

		// dao��model�Ķ���
		System.out.println("@Resource");
		System.out.println("private " + daoClassName + " dao;");
		System.out.println();
		System.out.println("private " + entityClassName + " model;");
		System.out.println();

		// ��ɾ�Ĳ�
		System.out.println("public String save(){");
		System.out.println(tab + "dao.save(model);");
		System.out.println(tab + "return \"listAction\";");
		System.out.println("}");
		System.out.println();

		System.out.println("public String delete(){");
		System.out.println(tab + "dao.delete(model);");
		System.out.println(tab + "return \"listAction\";");
		System.out.println("}");
		System.out.println();

		System.out.println("public String input(){");
		System.out.println(tab + "if( model!=null && model.getId()!=null ){");
		System.out.println(tab + tab + "model = dao.get(model.getId());");
		System.out.println(tab + "}");
		System.out.println(tab + "return \"input\";");
		System.out.println("}");
		System.out.println();

		System.out.println("public String list(){");
		System.out.println(tab + "List<" + entityClassName + "> datas = dao.gets();");
		System.out.println(tab + "set(\"datas\", datas);");
		System.out.println(tab + "");
		System.out.println("return \"list\";");
		System.out.println("}");
		System.out.println();

		// ---------------------------- set get
		System.out.println("//---------------------------- set get");
		System.out.println("public " + daoClassName + " getDao() {");
		System.out.println(tab + "return dao;");
		System.out.println("}");
		System.out.println();

		System.out.println("public void setDao(" + daoClassName + " dao) {");
		System.out.println(tab + "this.dao = dao;");
		System.out.println("}");
		System.out.println();

		System.out.println("public " + entityClassName + " getModel() {");
		System.out.println(tab + "return model;");
		System.out.println("}");
		System.out.println();

		System.out.println("public void setModel(" + entityClassName + " model) {");
		System.out.println(tab + "this.model = model;");
		System.out.println("}");
		System.out.println();

	}
	
	/**
	 * ���ʵ���jsp¼���޸�ҳ��
	 * @param clazz
	 * @param aciton struts2ӳ���action���
	 */
	public void printEntityJspInput(Class clazz, String aciton) {
		String prefix = "model.";
		String template = "<tr>" + "\n" + TAB + TAB + "<th>%text%</th>" + "\n" + TAB + TAB
				+ "<td><input type=\"text\" name=\"%name%\" value=\"%value%\" /></td>" + TAB + "\n" + TAB + "</tr>";

		List<String> filldsName = getFieldNames(clazz);

		printEntityJsp();
		System.out.println("<form action=\"<%=request.getContextPath()%>/" + aciton + "/action/" + aciton
				+ "!input.action\">");
		System.out.println("<table>");

		for (String n : filldsName) {
			String name = prefix + n;
			String value = "\\${" + name + "}";
			// String value = name;
			String html = TAB + template;
			html = html.replaceAll("%text%", n);
			html = html.replaceAll("%name%", name);
			html = html.replaceAll("%value%", value);
			System.out.println(html);
		}

		System.out.println(TAB + "<tr>");
		System.out.println(TAB + TAB
				+ "<td colspan=\"2\" style=\"text-align:center;\"><input type=\"submit\" value=\"����\" /></td>");
		System.out.println(TAB + "</tr>");

		System.out.println("</table>");
		System.out.println("</form>");
		System.out.println();
		System.out.println("</body>");
		System.out.print("</html>");
	}
	
	/**
	 * ���sqltype����java����
	 * 
	 * @param sqltype
	 *            Types�ĳ�
	 */
	private String getJavatype(int sqltype) {

		switch (sqltype) {
		case Types.VARCHAR:
			return "String";
		case Types.CHAR:
			return "String";
		case Types.DATE:
			return "Date";
		case Types.TIMESTAMP:
			return "Date";
		case Types.INTEGER:
			return "Integer";
		case Types.NUMERIC:
			return "BigDecimal";
		case Types.DECIMAL:
			return "BigDecimal";
		case Types.CLOB:
			return "String";
		case Types.BLOB:
			return "byte[]";
		default:
			throw new RuntimeException("δ֪��Types : " + sqltype);
		}
	}

	/**
	 * �����ݿ��ֶλ�ȡjava�����ֶ�
	 * 
	 * @param colname
	 *            eg:ROAD_CON_CITY
	 * @return
	 */
	private String getJavaname(String colname) {

		String[] cols = colname.split("_");
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < cols.length; i++) {
			String col = cols[i];
			String jname = col.toLowerCase();

			if (i != 0) {
				// ����ĸ��д
				jname = jname.substring(0, 1).toUpperCase() + jname.substring(1);
			}

			sb.append(jname);
		}
		return sb.toString();
	}
	
	
	
	/**
	 * �����ʾʵ���б��jsp
	 * 
	 * @param aciton
	 *            struts2ӳ���action���
	 */
	public void printEntityJspList(Class entityClass, String aciton) {

		String tab = TAB;

		printEntityJsp();

		// ��ݱ��
		List<String> fields = getFieldNames(entityClass);// ʵ�������
		// String name = entityClass.getSimpleName();
		System.out.println("<table class=\"dtable\">");
		System.out.println(tab + "<thead>");
		for (String f : fields) {
			System.out.println(tab + tab + "<td>" + f + "</td>");
		}
		System.out.println(tab + tab + "<td>����</td>");// ����
		System.out.println(tab + "</thead>");

		System.out.println(tab + "<tbody>");
		System.out.println(tab + tab + "<c:forEach items=\"${datas}\" var=\"d\">");
		System.out.println(tab + tab + tab + "<tr>");
		for (String f : fields) {
			System.out.println(tab + tab + tab + tab + "<td>${d." + f + "}</td>");
		}
		System.out.println(tab + tab + tab + tab + "<td>");
		System.out.println(tab + tab + tab + tab + tab + "<a href=\"<%=request.getContextPath()%>/" + aciton
				+ "/action/" + aciton + "!input.action\">�޸�</a>");
		System.out.println(tab + tab + tab + tab + tab + "<a href=\"<%=request.getContextPath()%>/" + aciton
				+ "/action/" + aciton + "!delete.action\" onclick=\"return confirm('ȷ��ɾ������¼?')\">ɾ��</a>");
		System.out.println(tab + tab + tab + tab + "</td>");
		System.out.println(tab + tab + tab + "</tr>");
		System.out.println(tab + tab + "</c:forEach>");
		System.out.println(tab + "</tbody>");
		System.out.println("</table>");

		System.out.println();
		System.out.println("</body>");
		System.out.print("</html>");

		/*
		 * 
		 * <tbody> <c:forEach items="${datas}" var="d"> <tr> <td>${d.xxx}</td>
		 * </tr> </c:forEach> </tbody> </table>
		 */
	}
	

	/**
	 * ���jsp���ò���
	 */
	private void printEntityJsp() {
		String encode = "GBK";
		System.out.println("<%@ page language=\"java\" contentType=\"text/html;charset=" + encode
				+ "\" pageEncoding=\"" + encode + "\"%>");
		System.out.println("<%@ taglib prefix=\"c\" uri=\"http://java.sun.com/jsp/jstl/core\" %>");
		System.out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		System.out.println("<html>");
		System.out.println("<head>");
		System.out.println("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=" + encode + "\">");
		System.out.println("<title></title>");
		System.out.println("</head>");
		System.out.println("<body>");
		System.out.println();
	}

}
